import os

def generate_table(rows, md_file=None, delimiter=',', float_precision=2):
    processed = []
    for row in rows:
        new_row = []
        for cell in row:
            cell = cell.replace('|', r'\|')
            try:
                num = float(cell)
                cell = f"{num:.{float_precision}f}".rstrip('0').rstrip('.') if '.' in cell else str(int(num))
            except ValueError:
                pass
            new_row.append(cell.strip())
        processed.append(new_row)

    headers = processed[0]
    separator = ['-' * len(h) for h in headers]
    md = [
        '| ' + ' | '.join(headers) + ' |',
        '|-' + '-|-'.join(separator) + '-|'
    ]
    md += ['| ' + ' | '.join(row) + ' |' for row in processed[1:]]

    if md_file:
        with open(md_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(md))
    return '\n'.join(md)


def generate_list(gpu_list):
    return '\n'.join(
        f"    - {val}"
        for val in gpu_list
        )

def generate_devcie_info(hw_info):

    device_str = f"""
## Device Info
- Os: {hw_info['os_name']}  
- Os Version: {hw_info['os_version']}
- Arch: {hw_info['arch']}
- Cpu: {hw_info['cpu_model']}
- Memory: {hw_info['mem_total']} GB
- Gpu List: 
{generate_list(hw_info['gpu_list'])}
    """
    return device_str


def generate_header():
    return f"""
# Benchmark Report
    """


def generate_compare(rows):
    return f"""
## Compare Overview
{generate_table(rows)}
    """


def generate_blas_compare(blas_file):
    return f"""
## Blas performance comparison 
![](./blas_performance_comparison.png "blas performance comparison")
    """


def generate_markdown(hw_info, rows, output_file_path, gen_blas=True):
    if gen_blas:
        markdown_str = f"""
{generate_header()}
{generate_devcie_info(hw_info)}
{generate_compare(rows)}
{generate_blas_compare(output_file_path + "blas_performance_comparison.png")}
    """
    else:
        markdown_str = f"""
{generate_header()}
{generate_devcie_info(hw_info)}
{generate_compare(rows)}
    """

    output_file = output_file_path + "result.md"
    if os.path.exists(output_file):
        os.remove(output_file)
    with open(output_file, 'w') as outfile:
        outfile.write(markdown_str) 
    print(f"Generate result at {output_file}")


